package cn.sdstudio.controller;

import cn.hutool.core.lang.Assert;
import cn.sdstudio.model.Result;
import cn.sdstudio.entity.Collect;
import cn.sdstudio.entity.RelicSite;
import cn.sdstudio.vo.FavoriteVO;
import cn.sdstudio.vo.RelicSiteVO;
import cn.sdstudio.service.RelicSiteService;
import cn.sdstudio.utils.JwtUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/relicSites")
@Slf4j
@RequiredArgsConstructor
public class RelicSiteController {

    private final RelicSiteService relicSiteService;

    private final JwtUtils jwtUtil;

    @GetMapping("/list")
    public Result<?> RemainList(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "4") Integer pageSize) {
        Page<RelicSite> page = new Page<>(currentPage, pageSize);
        IPage<RelicSite> remainsIPage = relicSiteService.page(page);
        return Result.success(remainsIPage);
    }


    @GetMapping("/detail/{id}")
    public Result<?> detail(@PathVariable(name = "id") Long id, @RequestHeader(name="token",required = false) String token) {
        RelicSite RelicSite = relicSiteService.getById(id);
        log.error(RelicSite.toString());
        Claims claims = jwtUtil.parseToken(token);
        long userId=0;
        try{
            userId= claims.get("userId",Long.class);
        }catch (Exception ignored){
        }
        RelicSiteVO relicSiteVo =new RelicSiteVO();
        relicSiteVo.setCover(RelicSite.getCoverImage())
                .setContent(RelicSite.getContent())
                .setName(RelicSite.getName())
                .setDescription(RelicSite.getDescription())
                .setCreatedAt(RelicSite.getCreateTime())
                .setUpdateAt(RelicSite.getUpdateTime())
                .setBrowseNum(RelicSite.getBrowseCount())
                .setSchedule(RelicSite.getLongitude())
                .setLatitude(RelicSite.getLatitude())
                .setTitle(RelicSite.getTitle())
                .setUrlPath(RelicSite.getUrlPath())
                .setId(RelicSite.getId());
        List<FavoriteVO> myCollect = relicSiteService.getMyCollect((int) userId);
        for (FavoriteVO favoriteVo : myCollect) {
            if (favoriteVo.getId() == id) {
                log.error("遗迹已收藏");
                relicSiteVo.setIsFavorite(1);
            }
        }
        Assert.notNull(relicSiteVo, "该遗迹文章已被删除");
        return Result.success(relicSiteVo);
    }

    @PostMapping("/edit")
    public Result<?> edit(@Validated @RequestBody RelicSite RelicSite) {
        boolean flag = relicSiteService.saveOrUpdate(RelicSite);
        return flag ? Result.success("操作成功") : Result.error(400,"操作失败");
    }


    @GetMapping("/delete/{id}")
    public Result<?> delete(@PathVariable(name = "id") Long id) {
        boolean flag = relicSiteService.removeById(id);
        return flag ? Result.success("删除成功") : Result.error(400,"该遗迹不存在");
    }

    @PostMapping("/add")
    public Result<?> add(@RequestBody @Validated RelicSite RelicSite) {
        RelicSite temp = null;
        if (RelicSite.getId() != null) {
            temp = relicSiteService.getById(RelicSite.getId());
        } else {
            temp = new RelicSite();
            log.error("temp:" + temp);
        }
        BeanUtils.copyProperties(RelicSite, temp, "created_at", "update_at");
        boolean flag = relicSiteService.save(temp);
        return flag ? Result.success("操作成功") : Result.error(400,"操作失败");
    }

    @GetMapping("/addcollect/{id}")

    public Result<?> addCollect(@PathVariable(name = "id") int id, @RequestHeader(name = "token") String token) {
        Claims claims = jwtUtil.parseToken(token);
        Assert.notNull(claims, "用户未登录");
        long userId = claims.get("userId",Long.class);
        List<FavoriteVO> myCollect = relicSiteService.getMyCollect((int) userId);
        for (FavoriteVO favoriteVo : myCollect) {
            log.error("id:" + favoriteVo.getId());
            if (favoriteVo.getId() == id) {
                return Result.error(400,"请勿重复添加收藏");
            }
        }
        relicSiteService.addCollect(new Collect()
                .setId(id)
                .setFavoriteTime(LocalDateTime.now())
                .setUserId((int) userId));
        return Result.success("添加成功");
    }


    @GetMapping("/favorites")
    public Result<?> myCollect(@RequestHeader(name = "token") String token) {
        Claims claims = jwtUtil.parseToken(token);
        Assert.notNull(claims, "用户未登录");
        long userId = claims.get("userId",Long.class);
        List<FavoriteVO> myCollect = relicSiteService.getMyCollect((int) userId);
        Assert.notNull(myCollect, "你没有收藏的遗迹");
        return Result.success(myCollect);
    }

    @GetMapping("/favorite/delete/{id}")
    public Result<?> deletemyCollect(@PathVariable int id, @RequestHeader(name = "token") String token) {
        Claims claims = jwtUtil.parseToken(token);
        Assert.notNull(claims, "用户未登录");
        long userId = claims.get("userId",Long.class);
        int i = relicSiteService.deleteFavorite(id, (int) userId);
        return i > 0 ? Result.success("删除成功") : Result.error(400,"该收藏不存在");
    }
}

